package cn.taofuxn.sale.service.impl;

import cn.taofuxn.sale.bean.TbConsumer;
import cn.taofuxn.sale.controller.data.AddConsumerRequest;
import cn.taofuxn.sale.controller.data.ModifyConsumerRequest;
import cn.taofuxn.sale.dao.ConsumerDao;
import cn.taofuxn.sale.service.ConsumerService;
import cn.taofuxn.sale.service.data.base.BasePageResponse;
import cn.taofuxn.sale.service.data.base.BaseResult;
import cn.taofuxn.sale.service.data.base.ResultCodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * ProjectName : GeekSaleSystem
 * PackageName : cn.taofuxn.sale.service.impl
 * Created by Wong
 * Date: 2018/4/12
 * Time: 19:09
 */
@Service
public class ConsumerServiceImpl implements ConsumerService {
	
	@Autowired
	private ConsumerDao m_ConsumerDao;
	
	@SuppressWarnings("Duplicates")
	@Override
	public BaseResult getConsumer(final int vPage, final int vPageSize) {
		PageRequest tPageRequest = new PageRequest(vPage, vPageSize);
		Page tConsumerPage = m_ConsumerDao.findAll(tPageRequest);
		BasePageResponse tResponse = new BasePageResponse();
		
		tResponse.setInfos(tConsumerPage.getContent());
		tResponse.setTotal((int) tConsumerPage.getTotalElements());
		tResponse.setTotalPage(tConsumerPage.getTotalPages());
		return BaseResult.success(tResponse);
	}
	
	@Override
	public BaseResult addConsumer(final AddConsumerRequest vRequest) {
		List<TbConsumer> tTbConsumers = m_ConsumerDao.findByName(vRequest.getName());
		if(! CollectionUtils.isEmpty(tTbConsumers)){
			return BaseResult.generate(ResultCodeType.CONSUMER_NAME_DUPLICATE);
		}
		
		TbConsumer tTbConsumer = new TbConsumer();
		tTbConsumer.setAddress(vRequest.getAddress());
		tTbConsumer.setNote(vRequest.getNote());
		tTbConsumer.setName(vRequest.getName());
		tTbConsumer.setPhone(vRequest.getPhone());
		return BaseResult.success(m_ConsumerDao.save(tTbConsumer));
		
	}
	
	@Override
	public BaseResult modifyConsumer(final ModifyConsumerRequest vRequest) {
		TbConsumer tTbConsumer= m_ConsumerDao.findOne(vRequest.getId());
		if(null == tTbConsumer){
			return BaseResult.generate(ResultCodeType.NOT_FOUND_CONSUMER);
		}
		
		tTbConsumer.setAddress(vRequest.getAddress());
		tTbConsumer.setNote(vRequest.getNote());
		tTbConsumer.setName(vRequest.getName());
		tTbConsumer.setPhone(vRequest.getPhone());
		return BaseResult.success(m_ConsumerDao.save(tTbConsumer));
	}
	
	@Override
	public BaseResult deleteConsumer(final String vOrderId) {
		// TODO: 2018/4/12  是否需要删除订单信息
		
		m_ConsumerDao.delete(vOrderId);
		return BaseResult.success();
	}
}
